package com.heima.article.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    //送消息，创建索引
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        kafkaTemplate.send("article.es.sync.topic", JSON.toJSONString(vo));
    }



    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        // minBehotTime = 2063
        // publish_time < minBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        // publish_time < minBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        // publish_time > maxBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 2);
        return ResponseResult.okResult(apArticles);
    }



    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;




    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        // 1. dto判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        // 2. 判断是新增还是修改
        Long id = dto.getId();
        if (id == null) {
            // 3 新增

            // 3.2 插入article表
            int articleResult = apArticleMapper.insert(apArticle);
            if (articleResult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            // 3.3 插入article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setIsForward(true);
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsComment(true);
            int configResult = apArticleConfigMapper.insert(config);
            if (configResult < 1) {
                throw new RuntimeException("配置表插入失败");
            }

            // 3.4 插入article_content表
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(apArticle.getId());
            articleContent.setContent(dto.getContent());
            int contentResult = apArticleContentMapper.insert(articleContent);
            if (contentResult < 1) {
                throw new RuntimeException("内容表插入失败");


            } else {
                // 4. 修改

                // 4.1 修改article表
                int articleUpdateResult = apArticleMapper.updateById(apArticle);
                if (articleUpdateResult < 1) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
                }

                // 4.2 修改article_content表
                LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
                // 修改的数据
                ApArticleContent articleContentone = new ApArticleContent();
                articleContentone.setContent(dto.getContent());

                int contentUpdateResult = apArticleContentMapper.update(articleContent, wrapper);
                if (contentUpdateResult < 1) {
                    throw new RuntimeException("内容表修改失败");
                }

            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public void sendIndexUpdate(ApArticle apArticle, String content) {

    }
    
    @Override
    @Async
    public void generate(Long articleId) {

        // 1. 查询ApArticleContent表，获得里面content数据
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent == null) {
            log.warn("文章内容不存在");
            return;
        }

        // 2. 创建一个数据集合Map，把上一步content数据赋值到map的content字段上
        Map<String, Object> map = new HashMap<>(1);
        map.put("content", JSON.parseArray(apArticleContent.getContent()));

        // 3. 调用Freemarker插件，生成HTML页面
        InputStream is = freemarkerGenerator.generate("article.ftl", map);

        // 4. 调用MinIO插件，上传HTML页面
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");

        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章为空");
            return;
        }

        apArticle.setStaticUrl(url);

        // 5. 更新ApArticle，修改里面static_url字段
        apArticleMapper.updateById(apArticle);
        //6发送消息，创建索引
        createArticleESIndex(apArticle,apArticleContent.getContent(),apArticle.getStaticUrl());

    }
    }



